import React, {Component} from 'react';
import GridTable from '../../components/display/gridTable';
import { Button, Tooltip, Row, Col, Select, message, Timeline, Card, Input, Modal, Divider } from 'antd';
import ScModal from '../../components/feedback/scModal';
import { invoiceList, invoiceInfo, invoiceSend } from '../../fetch/fetchApi';
import Message from "../message";
import OrderList from "./orderList";
const Option = Select.Option;

class Invoicelist extends Component {
  constructor () {
    super();
    this.state = {
      gridData: null,
      loadingmes: '查询',
      loading: !1,
      btnloading: !1,
      result: null,
      emailAddress: '',
      pagination: {
        total: 0
      },
      orderListModalVisible:false
    };
    this.init();
    window.LayoutTab && setTimeout(() => {
      this.queryChargeInfo();
    }, 1);
  }

  init () {
    this.query = {
      page: '1',
      pagecount: '10'
    };
    this.query['userId'] = window.LayoutTab.tabParam.userId;
    // 设置表头
    this.tableColumns = [
      {
        title: '开票类型',
        dataIndex: 'type',
        key: 'type',
        render: (text, record) => (<div>{text === 0 ? '充电订单开票' : '企业充值开票'}</div>)
      }, {
        title: '抬头',
        dataIndex: 'invoiceTitle',
        key: 'invoiceTitle',
        className: 'column-nowrap',
        render: (text, record) => (
          <Tooltip placement="topLeft" title={text} >
            {text}
          </Tooltip>)
      }, {
        title: '开票金额',
        dataIndex: 'invoiceAmount',
        key: 'invoiceAmount',
      }, {
        title: '发票类别',
        dataIndex: 'invoiceMaterial',
        key: 'invoiceMaterial',
        render: (text, record) => (<div>{text === 1 ? '纸质发票' : '电子发票'}</div>)
      }, {
        title: '发票类型',
        dataIndex: 'invoiceType',
        key: 'invoiceType',
        render: (text, record) => (<div>{text === 1 ? '普通发票' : '增值税发票'}</div>)
      }, {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        render: (text, record) => (<div>{text === 0 ? '待开票' : text === 1 ? '已开票' : '已寄出(已完成)'}</div>)
      }, {
        title: '收件人',
        dataIndex: 'name',
        key: 'name'
      }, {
        title: '联系电话',
        dataIndex: 'phone',
        key: 'phone'
      }, {
        title: '申请时间',
        dataIndex: 'applyTime',
        key: 'applyTime'
      }, {
        title: '操作',
        key: 'action',
        render: (text, record) => (
          <div className="action-wrap">
            <a href="javascript:void(0);" onClick={() => this.showInvoiceDetail({'invoiceId': record.invoiceId , 'invoiceAppkey': record.invoiceAppkey, 'outInvoiceId': record.outInvoiceId}, '发票详情')}>查看详情</a>
            <Divider type="vertical" />
            <a href="javascript:void(0);" onClick={() => this.showOrderListModal(record)}>订单明细</a>
          </div>
        )
      }
    ];
  }

  showOrderListModal=(record)=>{
    this.setState({
      orderListModalVisible:true,
      invoiceRecord:record
    })
  }

  // fetch DataSource
  async invoiceList () {
    this.setState({
      loading: !0,
      btnloading: !0
    });
    try {
      const resData = await invoiceList(this.query);
      let resObj = resData.data.data;
      if (resData.data.code === '200') {
        for (let r of resObj) {
          r['timeStart'] = r['timeStart'] + ' - ' + r['timeEnd'];
        }
        const pagination = {
          total: resData.data.pageLimit.totalCount,
          onShowSizeChange: (current) => {
            this.turnPage(current)
          },
          onChange:(current) => {
            this.turnPage(current)
          }
        }
        this.setState({
          pagination
        });
        return resObj;
      }
    } catch (e) {
      console.log(e);
    }
  }

  // 跳转页码
  turnPage (current) {
    this.query['page'] = current.toString();
    this.queryChargeInfo();
  }

  // 提交查询
  queryChargeInfo () {
    this.invoiceList().then((data) => {
      this.setState({
        loading: !1,
        btnloading: !1,
        gridData: data
      });
    });
  }

  // 注入电桩编号参数
  pileInputHandler (e) {
    this.query['stubId'] = e.target.value.toString();
  }

  // 注入电站名称
  powerStationInputHandler (e) {
    this.query['keywords'] = e.target.value.toString();
  }

  // 选择年份
  onDataChange (e) {
    if (e[1]-e[0] > 7 * 24 * 60 * 6e4) {
      message.warn('选择范围请在7天内', 1);
      return;
    };
    this.query['startTime'] = e[0] && e[0].format('YYYY.MM.DD HH:mm:ss').toString();
    this.query['endTime'] = e[1] && e[1].format('YYYY.MM.DD HH:mm:ss').toString();
  }

  // 显示发票详情
  showInvoiceDetail (obj, title) {
    this.setState({
      width: 800,
      modalVisible: !0,
      modalTitle: title
    });
    this.getInvoiceInfo(obj).then((data) => {
      this.setState({
        result: data
      });
    });
  }

  // fetch 发票详情
  async getInvoiceInfo (obj) {
    try {
      const resData = await invoiceInfo(obj);
      if (resData.data.code === '200') {
        return resData.data.data;
      }
    } catch (e) {
      console.log(e);
    }
  }

  searchChargeInfo () {
    this.query.page = '1';
    this.state.pagination.current = 1;
    this.setState({
      pagination: this.state.pagination
    });
    this.queryChargeInfo();
  }

  // 取消弹窗
  cancel () {
    this.setState({
      modalVisible: !1,
      confirmLoading: !1,
      emailAddress: ''
    });
  }

  // 注入状态参数
  statusInputHandler (v) {
    this.query['invoiceStatus'] = v;
  }

  // 新增邮箱地址绑定 -- start ↓↓

  changeEmailAddress (e) {
    this.setState({
      'emailAddress': e.target.value
    });
  }

  // 保存邮箱地址
  saveEmailAddress () {
    this.setState({
      loading: !0
    });
    this.postEmailAddress().then(() => {
      this.setState({
        loading: !1
      });
    });
  }

  // 请求邮箱地址

  async postEmailAddress () {
    try {
      let resData = await invoiceSend({
        email: this.state.emailAddress,
        invoiceAppkey: this.state.result.invoiceAppkey,
        invoiceId: this.state.result.invoiceId
      });
      if (resData.data.code.toString() === '200') {
        message.success('提交成功', 1);
        this.setState({
          'emailAddress': ''
        });
      }
    } catch (e) {
      console.log(e);
    }
  }

  // ↑↑

  handleOrderListModalCancel=()=>{
    this.setState({
      orderListModalVisible:false
    })
  }

  render () {
    const Content = <div className="sc-page-content">
      <div className="page-toolbar">
        <Row gutter={8}>
          <Col lg={8} xl={4}>
            <Select placeholder="开票状态" onChange={this.statusInputHandler.bind(this)}>
              <Option value="">全部</Option>
              <Option value="0">待开票</Option>
              <Option value="1">已开票</Option>
              <Option value="2">已寄出(已完成)</Option>
            </Select>
          </Col>
          <div  className="button-inlineBlock">
            <Button type="primary" onClick={this.searchChargeInfo.bind(this)} loading={this.state.loading}>{this.state.loadingmes}</Button>
          </div>
        </Row>
      </div>
      <div className="page-panel">
        <GridTable postyle="table-center" data={this.state.gridData} columns={this.tableColumns} loading={this.state.loading} pagination={this.state.pagination}/>
        <ScModal
          width={this.state.width}
          modalVisible={this.state.modalVisible}
          modalTitle={this.state.modalTitle}
          modalContent={<div className="sc-modal-scroll">
            <div className="modal-list">
              {this.state.result && <div className={"modal-flex"}>
                <div className={"modal-flex-1"}>
                  <h3 className={'flex-title'}><span>发票信息</span></h3>
                  <ul>
                    <li>
                      <strong>开票类型</strong>
                      <span>{this.state.result.type === '1' ? '充电订单开票' : '企业充值开票'}</span>
                    </li>
                    <li>
                      <strong>开票主体</strong>
                      <span>{this.state.result.businessType === 1 ? '个人' : '企业'}</span>
                    </li>
                    <li>
                      <strong>开票金额</strong>
                      <span>{this.state.result.invoiceAmount}</span>
                    </li>
                    <li>
                      <strong>发票类别</strong>
                      <span>{this.state.result.invoiceMaterial === 1 ? '纸质发票' : '电子发票'}</span>
                    </li>
                    <li>
                      <strong>发票类型</strong>
                      <span>{this.state.result.invoiceType === 1 ? '普通发票' : '增值专用发票'}</span>
                    </li>
                    {this.state.result.invoiceTitle && <li>
                      <strong>发票抬头</strong>
                      <span>{this.state.result.invoiceTitle}</span>
                    </li>}
                    {this.state.result.payerRegisterNo && <li>
                      <strong>税        号</strong>
                      <span>{this.state.result.payerRegisterNo}</span>
                    </li>}
                    {this.state.result.payerAccountNum && <li>
                      <strong>开户信息</strong>
                      <Tooltip placement="topLeft" title={this.state.result.payerAccountNum}>
                        <span>{this.state.result.payerAccountNum}</span>
                      </Tooltip>
                    </li>}
                    {this.state.result.name && <li>
                      <strong>收   件 人</strong>
                      <span>{this.state.result.name}</span>
                    </li>}
                    {this.state.result.phone && <li>
                      <strong>联系电话</strong>
                      <span>{this.state.result.phone}</span>
                    </li>}
                    {this.state.result.address && <li>
                      <strong>收件地址</strong>
                      <span>{this.state.result.address}</span>
                    </li>}
                    {this.state.result.expressMoney && <li>
                      <strong>快递费用</strong>
                      <span>{this.state.result.expressMoney}</span>
                    </li>}
                  </ul>
                </div>
                <div className={"modal-flex-1"}>
                  <h3 className={'flex-title'}><span>发票信息</span></h3>
                  <ul>
                    <li>
                      <strong>开票状态</strong>
                      <span>{this.state.result.status === 0 ? '待开票' : this.state.result.status === 1 ? '已开票' : this.state.result.invoiceMaterial !== 1 ? '已完成' : '已寄出'}</span>
                    </li>
                    {/*
                      新增添加邮箱地址 -- start
                    */}
                    {
                      this.state.result.invoiceMaterial !== 1 && this.state.result.status === 2 && <li>
                        <Card
                          style={{ width: 500 }}
                          cover={<img src={this.state.result.eInvoiceMiniUrl} />}
                        >
                          <Input type={'text'} value={this.state.emailAddress} placeholder={'输入邮箱地址'} onChange={this.changeEmailAddress.bind(this)}/>
                          <Button type="primary" className={'modal-sm-btn'} onClick={this.saveEmailAddress.bind(this)} loading={this.state.loading}>发送邮箱</Button>
                        </Card>
                      </li>
                    }
                    {/*
                      新增添加邮箱地址 -- end
                    */}
                    {this.state.result.expressName && <li>
                      <strong>快递名称</strong>
                      <span>{this.state.result.expressName}</span>
                    </li>}
                    {this.state.result.expressNum && <li>
                      <strong>快递单号</strong>
                      <span>{this.state.result.expressNum}</span>
                    </li>}
                  </ul>
                  <Timeline>
                    {this.state.result.progress && this.state.result.progress.map((r, index) => {
                      if (index === 0) {
                        return <Timeline.Item color="blue"><p>{r.time}</p><p>{r.detail}</p></Timeline.Item>;
                      } else {
                        return <Timeline.Item color="green"><p>{r.time}</p><p>{r.detail}</p></Timeline.Item>;
                      }
                    })
                    }
                  </Timeline>
                </div>
              </div>}
            </div>
          </div>}
          footer={null}
          cancel={this.cancel.bind(this)}
        />
      </div>
      <Modal width='850px' visible={this.state.orderListModalVisible} footer={null} onCancel={this.handleOrderListModalCancel} title={'订单明细'}>
        <OrderList record={this.state.invoiceRecord} />
      </Modal>
    </div>;

    return Content;
  }
}

export default Invoicelist;